package com.tilaiedu.mvc.handler;

import com.tilaiedu.mvc.common.R;
import com.tilaiedu.mvc.common.ResultCode;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * @Author xlzhang
 * @Date 2022/5/30 10:00
 * @Version 1.0
 * @Description TODO
 */
// @ControllerAdvice
// @ResponseBody
@RestControllerAdvice  // 基于前后端分离的异常统一处理注解
public class GlobalExceptionHandler {

    // 使用注解来指定当前方法要处理的具体异常
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(ArithmeticException.class)
    public R<Object> handlerArithmeticException(Model model, ArithmeticException ex){
        System.out.println("handlerArithmeticException = " + ex.getMessage());
        model.addAttribute("errInfo",ex.getMessage());
        //ResponseEntity
        return R.error(ex.getMessage());
    }

    // 404
    @ResponseStatus(HttpStatus.NOT_FOUND)   // 这个设置的是http协议的状态码，给浏览器
    @ExceptionHandler(NoHandlerFoundException.class)
    public R<Object> handlerNoHandlerFoundException(Model model, NoHandlerFoundException ex){
        System.out.println("handlerNoHandlerFoundException = " + ex.getMessage());
        model.addAttribute("errInfo",ex.getMessage());
        return R.error(ResultCode.NOT_FOUND);  // 这是业务状态码，是给前端开发人员用的
    }

    // @ExceptionHandler(FileNotFoundException.class)
    // public String handlerArithmeticException(Model model, FileNotFoundException ex){
    //     System.out.println("ex = " + ex.getMessage());
    //     model.addAttribute("msg",ex.getMessage());
    //     return "500";
    // }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Throwable.class)
    public R<Object> handlerException(Model model, Throwable ex){
        System.out.println("handlerException = " + ex.getMessage());
        model.addAttribute("errInfo",ex.getMessage());
        return R.error(ex.getMessage());
    }

}
